package com.demomaster.quickaccessibility.model;

import android.graphics.Rect;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.ArrayList;
import java.util.List;

public class QuickAccessibilityNodeInfo {
    AccessibilityNodeInfo node;
    String nodeToString;
    List<QuickAccessibilityNodeInfo> childList;

    public QuickAccessibilityNodeInfo(AccessibilityNodeInfo accessibilityNodeInfo) {
        this.node = accessibilityNodeInfo;
        //this.nodeToString = node.toString();
    }

    public void setNode(AccessibilityNodeInfo nodeInfo) {
        this.node = nodeInfo;
        //刷新
        //this.nodeToString = node.toString();
    }

    public AccessibilityNodeInfo getNode() {
        return node;
    }

    public List<QuickAccessibilityNodeInfo> getChildList() {
        //if (TextUtils.isEmpty(nodeToString) || !nodeToString.equals(node.toString())) {
            if (childList != null) {
                childList.clear();
            } else {
                childList = new ArrayList<>();
            }
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo accessibilityNodeInfo = node.getChild(i);
                if (accessibilityNodeInfo != null) {
                    childList.add(new QuickAccessibilityNodeInfo(accessibilityNodeInfo));
                }
            }

            //刷新
            this.nodeToString = node.toString();
        //}
        return childList;
    }

    public int getChildCount() {
        return node.getChildCount();
    }

    public QuickAccessibilityNodeInfo getChild(int i) {
        if (getChildList() == null || i >= getChildList().size()) {
            return null;
        }
        return getChildList().get(i);
    }

    //Rect boundsInScreenRect;
    public Rect getBoundsInScreenRect() {
//        if(boundsInScreenRect==null) {
//            boundsInScreenRect = new Rect();
//        }
        Rect rect = new Rect();
        node.getBoundsInScreen(rect);
 //       Rect rect1 = QuickAccessibilityHelper.getBundsInScreen(node);
//        if (!areRectsEqual(rect, rect1)) {
//            Log.e("QuickAccessibilityNodeInfo", "不匹配: " + rect + "  " + rect1);
//        }
        return rect;
    }
    public static boolean areRectsEqual(Rect rect1, Rect rect2) {
        return rect1.left == rect2.left &&
                rect1.top == rect2.top &&
                rect1.right == rect2.right &&
                rect1.bottom == rect2.bottom;
    }

    //Rect boundsInParentRect;
    public Rect getBoundsInParentRect() {
//        if(boundsInParentRect==null) {
//            boundsInParentRect = new Rect();
//        }
        Rect rect = new Rect();
        node.getBoundsInParent(rect);
        return rect;
    }

}
